package com.zhangxu.microservice.system.biz.service.impl;

import com.zhangxu.microservice.common.exception.BizException;
import com.zhangxu.microservice.common.utils.ListUtils;
import com.zhangxu.microservice.system.biz.dto.EmployeeDTO;
import com.zhangxu.microservice.system.biz.dto.EmployeeRoleDTO;
import com.zhangxu.microservice.system.biz.dto.LoginReqDTO;
import com.zhangxu.microservice.system.biz.dto.TokenRespDTO;
import com.zhangxu.microservice.system.biz.service.AuthService;
import com.zhangxu.microservice.system.biz.service.EmployeeBizService;
import com.zhangxu.microservice.system.biz.service.EmployeeRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final EmployeeBizService employeeBizService;
    private final TokenService tokenService;
    private final PasswordEncoder passwordEncoder;
    private final EmployeeRoleService employeeRoleService;

    @Override
    public TokenRespDTO login(LoginReqDTO reqDTO) {
        EmployeeDTO employeeDTO = employeeBizService.getByAccount(reqDTO.getAccount());
        if (employeeDTO == null) {
            throw new BizException("账号或密码不正确");
        }
        if (!passwordEncoder.matches(reqDTO.getPassword(), employeeDTO.getPasswordCrypto())) {
            throw new RuntimeException("账号或密码不正确");
        }
        String token = tokenService.generateAndCacheToken(employeeDTO.getId(), employeeDTO.getName());
        //查询当前账户拥有的角色列表
        List<EmployeeRoleDTO> employeeRoleDTOS = employeeRoleService.getByEmployeeId(employeeDTO.getId());
        //获取当前启用的角色ID
        List<Long> roleIds = ListUtils.mapList(employeeRoleDTOS, EmployeeRoleDTO::getRoleId);
        return new TokenRespDTO(employeeDTO.getId().toString(), employeeDTO.getAccount(), employeeDTO.getName(), token, roleIds);
    }
}